<template>
  <div>
    <a-modal
      :maskClosable="false"
      :title="title"
      centered
      :width="800"
      v-model="visible"
      :bodyStyle="{ paddingTop: '10px' }"
      @ok="submit"
    >
      <a-form-model :model="tagForm" :rules="rules" ref="ruleForm" :labelCol="labelCol" :wrapperCol="wrapperCol">
        <a-form-model-item label="标签分组：" prop="belongId">
          <a-select v-model="tagForm.belongId" placeholder="请选择标签分组">
            <a-select-option :value="0">默认分组</a-select-option>
            <a-select-option v-for="item in groupData" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="名称：" prop="name">
          <a-input v-model.trim="tagForm.name" placeholder="请输入标签名称" />
        </a-form-model-item>
        <a-form-model-item label="是否对外展示：" prop="isShow">
          <a-select v-model="tagForm.isShow" placeholder="请选择">
            <a-select-option :value="0">是</a-select-option>
            <a-select-option :value="1">否</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { addTag, updateTag } from '@/api/member/grouping'

export default {
  props: ['groupData'],
  data() {
    return {
      visible: false,
      title: '',
      tagForm: {
        name: '',
        belongId: 0,
        isShow: 1,
        id: undefined
      },
      type: '0',  // 0 用户标签 1 单位标签
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      rules: {
        belongId: [{ required: true, message: '标签分组不能为空', trigger: 'change' }],
        name: [{ required: true, message: '标签名称不能为空', trigger: 'blur' },
        { min: 1, max: 20, message: '标签名称字符限制为1~20', trigger: 'blur' }]
      }
    }
  },
  methods: {
    show(type, row) {
      this.type = type
      if (row) {
        this.title = '编辑标签'
        this.tagForm.id = row.id
        this.tagForm.name = row.name
        this.tagForm.belongId = row.belongId
        this.tagForm.isShow = row.isShow
      } else {
        this.title = '新增标签'
        Object.assign(this.$data.tagForm, this.$options.data().tagForm)
      }
      this.visible = true
    },
    submit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.tagForm.id) {
            updateTag({ type: this.type, ...this.tagForm }).then(() => {
              this.$message.success('修改成功')
              this.$emit('refreshTag')
              this.visible = false
            })
          } else {
            addTag({ type: this.type, ...this.tagForm }).then((res) => {
              this.$message.success('新增成功')
              this.$emit('refreshTag',res.data)
              this.visible = false
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
